package com.lg.my.netty.codec;

import com.lg.netty.codec.ProtostuffUtil;
import com.lg.netty.codec.User;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @author by Mr. Li 2021/4/22 2:30
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到服务器消息:" + msg);
    }

    /**
     * 当channel 创建完成时回调
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("MyClientHandler发送数据");
        //ctx.writeAndFlush("测试String编解码");
        //ctx.writeAndFlush(new User(1, "xiaogang"));

        // 使用protocol 进行编码
        //final ByteBuf byteBuf = Unpooled.copiedBuffer(ProtostuffUtil.serializer(new User(1, "xiaogang")));
        //ctx.writeAndFlush(byteBuf);

        ctx.writeAndFlush(new User(1, "xiaogang"));

    }
}
